<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import type { FormInstance } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";
import $request from "../request";

// 组件定义
const formRef = ref<FormInstance>();

// 状态参数
const state = reactive({
  confirmLoading: false
});

// 表单数据
const formData = ref({
  nickname: "",
  phone: "",
  email: "",
  remark: ""
});

// 加载用户信息
const loadUserInfo = () => {
  formData.value.nickname = useUserStoreHook().nickname;
  formData.value.phone = useUserStoreHook().phone;
  formData.value.email = useUserStoreHook().email;
  formData.value.remark = useUserStoreHook().remark;
};

// 更新信息
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      try {
        state.confirmLoading = true;
        await $request.put.updateUserInfo(formData.value);
        message("更新成功", { type: "success" });
        await useUserStoreHook().refreshUserInfo();
        loadUserInfo();
      } finally {
        state.confirmLoading = false;
      }
    }
  });
};

onMounted(() => {
  loadUserInfo();
});
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    label-position="top"
    label-width="auto"
  >
    <el-form-item
      label="昵称"
      prop="nickname"
      :rules="[{ required: true, message: '昵称必填' }]"
    >
      <el-input v-model="formData.nickname" placeholder="请输入昵称" />
    </el-form-item>
    <el-form-item label="手机">
      <el-input v-model="formData.phone" placeholder="请输入手机" />
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="formData.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-form-item label="个人备注">
      <el-input
        v-model="formData.remark"
        type="textarea"
        :rows="5"
        placeholder="请输入个人备注"
        maxlength="100"
        show-word-limit
      />
    </el-form-item>
    <el-form-item>
      <el-button
        :loading="state.confirmLoading"
        type="primary"
        plain
        @click="onSubmit(formRef)"
      >
        更新个人信息
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
//
</style>
